const router = require('koa-router')()
const jwt = require('jsonwebtoken')

// router.prefix('/users')

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

router.get('/api/users', function (ctx, next) {
  ctx.body = {
    code: 0,
    data: 'this is a users/bar response',
  }
})

router.post('/api/upload', function (ctx, next) {
  // 文件上传成功之后，需要返回给用户一个线上地址
  // http://localhost:3000 / images /1.jpg
  const file = ctx.request.files.file
  const fileName = file.path.split('images/')[1]
  ctx.body = {
    url: `http://localhost:3000/images/${fileName}`,
  }
})

router.post('/api/login', async (ctx, next) => {
  const { userId, username, password } = ctx.request.body
  const token = jwt.sign({ username }, '2009A', { expiresIn: '24h' })
  ctx.body = {
    code: 0,
    data: token,
  }
})

// rbac
// token + superAdmin
// token + admin
router.get('/api/routes', async function (ctx, next) {
  const { token } = ctx.request.header // token一般会携带在请求头中
  console.log('后单呢：', token)
  try {
    // 1. 解析token
    const { username } = jwt.verify(token, '2009A')
    // console.log(data, '--------------------')
    // 2. 拿到信息匹配数据
    if (username == 'zhangsan') {
      ctx.body = {
        code: 0,
        data: [
          {
            id: 1,
            path: '/basic/dashboard',
            text: '仪表盘',
          },
          {
            id: 2,
            path: '/basic/counter',
            text: '计数',
          },
          {
            id: 3,
            path: '/basic/cart',
            text: '购物车',
          },
          {
            id: 4,
            path: '/basic/book',
            text: '书城',
          },
        ],
      }
    } else {
      ctx.body = {
        code: 0,
        data: [
          {
            id: 1,
            path: '/basic/cart',
            text: '购物车',
          },
          {
            id: 2,
            path: '/basic/book',
            text: '书城',
          },
        ],
      }
    }
  } catch (error) {
    ctx.body = { code: -1, error }
  }
})

module.exports = router
